const express = require('express')
const cors = require('cors')
const app = express()
const { writeFile, readFile } = require('./filedata')
const md5 = require('md5')
const jwt = require('jsonwebtoken')
const mongoose = require('mongoose')


app.use(cors())

app.use(express.urlencoded())
app.use(express.json())

let dbUrl = 'mongodb://127.0.0.1:27017/product'
mongoose.connect(dbUrl).then((resolve) => { console.log('数据库连接成功') })
const { Schema } = mongoose
const userSchema = new Schema({
    username: String,
    password: String,
    tel: Number,
    userId: Number
})
//用户表
const User = mongoose.model('user', userSchema)

// const listSchema = new Schema({
// 
// })
// const List = mongoose.model('list', listSchema)
async function saveData() {
    const result = JSON.parse(await readFile('./user.json'))
    console.log(result)
    User.create(result)
}
// saveData()

app.get('/', (req, res, next) => {
    res.send('服务启动')
})

app.post("/register", async (req, res, next) => {

    let { tel, password, ypassword, username } = req.body
    if (tel && password && ypassword) {
        let result = await User.findOne({ username })
        if (result) {
            return res.json({ msg: "用户名已经存在" })
        }
        if (password != ypassword) {
            return res.json({ msg: "两次密码必须保持一致" })
        }
        if (password.length <= 8) {
            return res.json({ msg: "密码格式错误,密码长度必须大于8位" })
        }
        next();
    } else {
        return res.json({ msg: "注册失败,参数错误" })
    }
}, async (req, res, next) => {
    let { tel, password, ypassword, username } = req.body
    password = md5(password)
    let result = await User.create({
        tel, password, username, typeId: 0
    })
    console.log(result)
    return res.json({ msg: "注册成功", data: result })

})

let verifyToken = (req, res, next) => {
    let token = req.body.token
    if (token) {
        token = token.split(' ')[1]
        jwt.verify(token, 'vihc bifa dada', async (err, data) => {
            if (err) {
                if (err.message == 'jwt expired') {
                    return res.status(401).json({ msg: 'token过期' })
                } else if (err.message == 'invalid token') {
                    return res.status(401).json({ msg: 'token无效' })
                }
                res.status(401).json({ msg: err.message })
            } else {

                next()
            }

        })
    } else {
        res.status(400).json({ msg: '未找到有效token' })
    }
}
// 登录接口
app.post("/login", async (req, res, next) => {
    //尝试body传入token,成功
    let token = req.body.token
    if (token) {
        token = token.split(' ')[1]

        jwt.verify(token, 'vihc bifa dada', async (err, data) => {
            if (err) {
                if (err.message == 'jwt expired') {
                    return res.status(401).json({ msg: 'token过期' })
                } else if (err.message == 'invalid token') {
                    return res.status(401).json({ msg: 'token无效' })
                }
                res.status(401).json({ msg: err.message })
            } else {

                res.status(200).json({
                    msg: '登录成功', data
                })
            }
        })
    } else {
        let { tel, password } = req.body
        if (tel && password) {
            password = md5(password)
            const [findOne] = await User.find({ tel }, { _id: 1, tel: 1, password: 1 })
            //查询结果
            if (findOne) {
                // 查到之后,密码必须一致才可登录
                if (findOne.password != password) {
                    return res.status(200).json({ msg: '密码不正确' })
                } else {
                    res.status(200).json({
                        msg: '登录成功',
                        code: 200,
                        token: "Bearer " + jwt.sign({
                            id: findOne._id.toString(),
                            password: findOne.password
                        }, 'vihc bifa dada', {
                            expiresIn: '10h'
                        })
                    })
                }
                // 查不到登录失败
            } else {
                res.status(200).json({ msg: '此账号不是会员,前去注册' })
            }

        } else {
            //传参错误,登录失败
            res.status(200).json({ msg: '参数错误' })
        }
    }
})

app.use(async function (err, req, res, next) {
    console.log("错误中间件", err.name)
    res.status(500).json({ err, msg: "服务器内部错误" })
})

//启动服务
app.listen('8090', () => {
    console.log('http://127.0.0.1:8090 服务器启动')
})